package com.jianan.mis.app.basedata;

import static com.jianan.mis.util.ui.calendar.SWTCalendarWrapper.openCalendar;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.domain.Department;
import com.jianan.mis.service.DepartmentService;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;

@SuppressWarnings("unchecked")
public class DepartmentView extends ViewPart {

	private StyledText txtRemark;
	private Text txtContractEndDate;
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	class ListLabelProvider extends LabelProvider {
		public String getText(Object element) {
			Department department = (Department) element;
			return department.getName();
		}
		public Image getImage(Object element) {
			return null;
		}
	}
	private ComboViewer departmentComboViewer;
	private Combo departmentCombo;
	private Text txtContractStartDate;
	private Text txtRemainingDeposit;
	private Text txtTotalDeposit;
	private Text txtName;
	public static final String ID = "com.jianan.mis.app.basedata.DepartmentView"; //$NON-NLS-1$

	final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	
	private DepartmentService departmentService;
	
	private Department currentDepartment;

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		
		if(!initializeServices()) {
			MessageDialog.openError(getViewSite().getShell(),
					IMessageKeys.OPEN_VIEW_FAIL, IMessageKeys.SERVICE_UNAVAILABLE);
			return;
		}
		
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.makeColumnsEqualWidth = true;
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label.setText("选择部门:");

		departmentComboViewer = new ComboViewer(container, SWT.READ_ONLY);
		departmentComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(final SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event.getSelection();
				currentDepartment = (Department) selection.getFirstElement();
				txtName.setText(currentDepartment.getName());
				txtTotalDeposit.setText(currentDepartment.getTotalDeposit().toString());
				txtRemainingDeposit.setText(departmentService.getRemainingDeposit(currentDepartment.getId()).toString());
				txtContractStartDate.setText(simpleDateFormat.format(currentDepartment.getContractStartDate()));
				txtContractEndDate.setText(simpleDateFormat.format(currentDepartment.getContractEndDate()));
				txtRemark.setText(currentDepartment.getRemark());
			}
		});
		departmentComboViewer.setContentProvider(new ContentProvider());
		departmentComboViewer.setLabelProvider(new ListLabelProvider());
		departmentCombo = departmentComboViewer.getCombo();
		departmentCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		final GridData gd_combo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_combo.widthHint = 45;
		departmentCombo.setLayoutData(gd_combo);
		departmentComboViewer.setInput(departmentService.getAll());

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_1.setText("名称:");

		txtName = new Text(container, SWT.BORDER);
		final GridData gd_txtName = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		txtName.setLayoutData(gd_txtName);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_2.setText("押金总额度:");

		txtTotalDeposit = new Text(container, SWT.BORDER);
		final GridData gd_txtTotalDeposit = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_txtTotalDeposit.widthHint = 100;
		txtTotalDeposit.setLayoutData(gd_txtTotalDeposit);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_3.setText("押金剩余额度:");

		txtRemainingDeposit = new Text(container, SWT.BORDER);
		txtRemainingDeposit.setEditable(false);
		final GridData gd_txtRemainingDeposit = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_txtRemainingDeposit.widthHint = 100;
		txtRemainingDeposit.setLayoutData(gd_txtRemainingDeposit);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
		label_4.setText("合同起始日期:");

		txtContractStartDate = new Text(container, SWT.BORDER);
		txtContractStartDate.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtContractStartDate, simpleDateFormat);
			}
		});
		txtContractStartDate.setEditable(false);
		final GridData gd_txtContractStartDate = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContractStartDate.widthHint = 95;
		txtContractStartDate.setLayoutData(gd_txtContractStartDate);
		new Label(container, SWT.NONE);

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_5.setText("合同终止日期:");

		txtContractEndDate = new Text(container, SWT.BORDER);
		txtContractEndDate.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtContractEndDate, simpleDateFormat);
			}
		});
		txtContractEndDate.setEditable(false);
		final GridData gd_txtContractEndDate = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContractEndDate.widthHint = 95;
		txtContractEndDate.setLayoutData(gd_txtContractEndDate);
		new Label(container, SWT.NONE);

		final Label label_6 = new Label(container, SWT.NONE);
		label_6.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false));
		label_6.setText("备注:");

		txtRemark = new StyledText(container, SWT.V_SCROLL | SWT.MULTI | SWT.H_SCROLL | SWT.BORDER);
		final GridData gd_txtRemark = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
		gd_txtRemark.widthHint = 200;
		gd_txtRemark.heightHint = 60;
		txtRemark.setLayoutData(gd_txtRemark);

		final Button btnSave = new Button(container, SWT.NONE);
		btnSave.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (checkInfo()) {
					Department department = new Department();
					fillDepartmentFields(department);
					try {
						departmentService.save(department);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "新增部门信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnSave = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
		btnSave.setLayoutData(gd_btnSave);
		btnSave.setText("添加部门");

		final Button btnUpdate = new Button(container, SWT.NONE);
		btnUpdate.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentDepartment == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个部门!");
					return;
				}
				if (checkInfo()) {
					fillDepartmentFields(currentDepartment);
					try {
						departmentService.update(currentDepartment);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "更新部门信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
						return;
					}
				}
			}
		});
		final GridData gd_btnUpdate = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnUpdate.setLayoutData(gd_btnUpdate);
		btnUpdate.setText("更新部门");

		final Button btnRemove = new Button(container, SWT.NONE);
		btnRemove.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if(currentDepartment == null) {
					MessageDialog.openInformation(e.display.getActiveShell(), 
							IMessageKeys.FAIL, "请选择一个部门!");
					return;
				}
				if(MessageDialog.openConfirm(e.display.getActiveShell(), 
						IMessageKeys.CONFIRM, "确认删除该部门吗?")) {
					try {
						departmentService.remove(currentDepartment);
						reset();
						MessageDialog.openInformation(e.display.getActiveShell(), 
								IMessageKeys.SUCCESS, "删除部门信息成功!");
					} catch(Exception ex) {
						MessageDialog.openError(e.display.getActiveShell(),
								IMessageKeys.FAIL, ex.getMessage());
					}
				}
			}
		});
		btnRemove.setText("删除部门");
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	private boolean initializeServices() {
		departmentService = (DepartmentService) SpringBeanFactory.getBean("departmentService");
		if(departmentService == null) {
			return false;
		}
		return true;
	}
	
	private void reset() {
		txtName.setText("");
		txtTotalDeposit.setText("");
		txtRemainingDeposit.setText("");
		txtContractStartDate.setText("");
		txtContractEndDate.setText("");
		txtRemark.setText("");
		departmentComboViewer.setInput(departmentService.getAll());
		currentDepartment = null;
	}
	
	private void fillDepartmentFields(Department department) {
		department.setName(txtName.getText());
		department.setTotalDeposit(new BigDecimal(txtTotalDeposit.getText()).setScale(2, BigDecimal.ROUND_HALF_UP));
		try {
			department.setContractStartDate(simpleDateFormat.parse(txtContractStartDate.getText()));
			department.setContractEndDate(simpleDateFormat.parse(txtContractEndDate.getText()));
		} catch (ParseException ex) {
			ex.printStackTrace();
		}
		department.setRemark(txtRemark.getText());
	}
	
	private boolean checkInfo() {
		if(StringUtils.isEmpty(txtName.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入部门名称!");
			txtName.setFocus();
			return false;
		}
		if(StringUtils.isEmpty(txtTotalDeposit.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入押金总额度!");
			txtTotalDeposit.setFocus();
			return false;
		}
		if(!NumberUtils.isNumber(txtTotalDeposit.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "押金总额度输入错误，请重新输入!");
			txtTotalDeposit.setFocus();
			return false;
		}
		if(StringUtils.isEmpty(txtContractStartDate.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入合同起始日期!");
			txtContractStartDate.setFocus();
			return false;
		}
		if(StringUtils.isEmpty(txtContractEndDate.getText())) {
			MessageDialog.openError(getViewSite().getWorkbenchWindow().getShell(), 
					IMessageKeys.INFORMATION, "请输入合同终止日期!");
			txtContractEndDate.setFocus();
			return false;
		}
		return true;
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
